package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
)

type DeviceInfo struct {
	NPU         string
	Name        string
	Health      string
	PowerW      string
	TempC       string
	Chip        string
	Device      string
	BusID       string
	AICore      string
	MemoryUsed  string
	MemoryTotal string
}

func main() {
	file, err := os.Open("./gpu_demo/demo2.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)

	var blocks []string
	var currentBlock strings.Builder
	var devices []DeviceInfo

	// 扫描并分割块
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "+===================") || strings.HasPrefix(line, "+------------") {
			if currentBlock.Len() > 0 {
				blocks = append(blocks, currentBlock.String())
				currentBlock.Reset()
			}
		} else {
			currentBlock.WriteString(line)
			currentBlock.WriteByte('\n')
		}
	}

	// 处理 scanner 错误
	if err = scanner.Err(); err != nil {
		panic(err)
	}

	// 自定义替换函数，一次性替换多个字符为空格
	replaceChars := func(r rune) rune {
		switch r {
		case '\n', '|', '/', ' ': // 替换这些字符为空格
			return ' '
		default:
			return r
		}
	}

	for _, block := range blocks {
		block = strings.Map(replaceChars, block)
		if !strings.Contains(block, "NPU") && !strings.Contains(block, "npu-smi") {
			// 去除多余的空格
			fields := strings.Fields(block)

			// 确保字段数量足够
			if len(fields) >= 13 {
				device := DeviceInfo{
					NPU:         fields[0],
					Name:        fields[1],
					Health:      fields[2],
					PowerW:      fields[3],
					TempC:       fields[4],
					Chip:        fields[7],
					Device:      fields[8],
					BusID:       fields[9],
					AICore:      fields[10],
					MemoryUsed:  fields[11],
					MemoryTotal: fields[12],
				}
				devices = append(devices, device)
			} else {
				log.Printf("Skipping block due to insufficient fields: %d", len(fields))
			}
		}

	}

	// 打印结果
	for _, d := range devices {
		fmt.Printf("%+v\n", d)
	}
}
